package ar.com.ctrln.view.dashboard.mantenimiento.ticket;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

import org.zkoss.spring.security.SecurityUtil;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.EventQueue;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Footer;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import ar.com.ctrln.view.render.mantenimiento.ticket.TicketRowRender;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

import ar.com.ctrln.persistence.dao.ticket.*;
import ar.com.ctrln.persistence.model.cliente.Cliente;
import ar.com.ctrln.persistence.model.compra.Compra;
import ar.com.ctrln.persistence.model.sistema.cuentas.Autorizacion;
import ar.com.ctrln.persistence.model.sistema.cuentas.Usuario;
import ar.com.ctrln.persistence.model.ticket.Ticket;
import ar.com.ctrln.control.mantenimiento.ticket.ConsultarTicket;
import ar.com.ctrln.control.mantenimiento.ticket.RegistrarTicket;

@SuppressWarnings("unused")
@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ConsultarTicketController extends AbstractMinimizarVentana{

	private static final long serialVersionUID = 4448027582905493675L;

	@WireVariable
	private ConsultarTicket consultarTicket;
	
	@Wire
	private Window wConsultarTicket;
	
	@Wire
	private Grid ticketsGrid;
	
	@Wire
	private Button btnGrid;
	
	@Wire
	private Footer footer_category;
	
	@Wire
	private Footer footer_msg;
	
	@Wire("#txtFilter")
	private Textbox txtFilter;

	@Wire
	private Label footer_label;
	
	@Wire
	private Checkbox chkFiltroTickets;
	
	private List<Ticket> tickets;
	
	private ListModelList<Ticket> modelo;
	
	private Usuario user;

	private EventQueue<Event> eq = EventQueues.lookup("ticketsRefresh", EventQueues.DESKTOP, true);
	
	private EventQueue<Event> eq1 = EventQueues.lookup("ticketsUpdate", EventQueues.DESKTOP, true);
	
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		
        eq.subscribe(new EventListener<Event>() {
            public void onEvent(Event event) throws Exception {
            	ticketsGrid.setModel(getConsultaTicket());
            }});
        
        eq1.subscribe(new EventListener<Event>() {
            public void onEvent(Event event) throws Exception {
            	ticketsGrid.setModel(getConsultaTicket());
            }});
        
		ticketsGrid.setModel(getConsultaTicket());
		
	}
	
	public ListModel<Ticket> getConsultaTicket() {
		user = (Usuario)SecurityUtil.getAuthentication().getPrincipal();
		Set<Autorizacion> autorizaciones = (Set<Autorizacion>) user.getAuthorities();
		boolean isAuthored= false;
		for (Autorizacion auto : autorizaciones){
			if(auto.getAuthority().equals("ROLE_ADMIN"))
				isAuthored=true;
		}
		
		if(isAuthored){
		tickets = consultarTicket.listaTicketOrder();
		}
		else{
			tickets = consultarTicket.listaTicketxEmisor(user.getContacto().getOrganizacion().getId());
		}
		
		modelo= new ListModelList<Ticket>(tickets);
		return modelo;
	}

	/////////////////////////////FUNCION FILTRO////////////////////////////
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Listen("onChanging = #txtFilter")
	public void getFilter(Event event) {
		((Textbox) event.getTarget())
				.setValue(((org.zkoss.zk.ui.event.InputEvent) event).getValue());
		ticketsGrid.setModel(new ListModelList(getFilterBy(txtFilter.getValue(),modelo.getInnerList())));
		if (ticketsGrid.getRows().getChildren().size() > 0) {
			footer_msg.setLabel("");
			footer_category
					.setLabel("Un total de "
							+ ticketsGrid.getRows().getChildren().size()
							+ " Tickets");
		} else { 
			footer_msg.setLabel("Ningun Resultado...");
			footer_category.setLabel("");
		}
		((Textbox) event.getTarget()).setFocus(true);
	}
	
	public static List<Ticket> getFilterBy(String condicion, Collection<Ticket> tickets) {
		List<Ticket> data = new ArrayList<Ticket>();
		for (Iterator<Ticket> i = tickets.iterator(); i.hasNext();) {
			Ticket tmp = i.next();
			if (tmp.getOrganizacion().getRazonSocial().toLowerCase()
					.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getTipoTicket().getNombre().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0
							|| tmp.getEstado().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0) {
				data.add(tmp);
			}
		}
		return data;
	}
	/////////////////////////////FUNCION FILTRO////////////////////////////

	@Listen("onClick = #btnGrid")
	public void cerraVentana(Event event) {
		eq.close();
		wConsultarTicket.onClose();
	}
	
	@Listen("onClick = #btnImprimir")
	public void generarReporte() throws SQLException{
		Executions.createComponents("/zul/mantenimiento/tickets/filtrarTickets.zul",
				wConsultarTicket, null);		
	}
	
	@Listen("onClick = #chkFiltroTickets")
	public void mostrarPendientes(Event event) {
		List<Ticket> data = new ArrayList<Ticket>();
		modelo.clear();
		if(chkFiltroTickets.isChecked())
		{
			for (Ticket tick : tickets){
				if(!(tick.getEstado().equals(Ticket.ESTADO_CERRADO) || tick.getEstado().equals(Ticket.ESTADO_CANCELADO)
						|| tick.getEstado().equals(Ticket.ESTADO_ENESPERA)))
					data.add(tick);
			}
			modelo.addAll(data);
		}
		else{
			modelo.addAll(tickets);
		}
		ticketsGrid.setModel(modelo);
	}
	
	
	
}
